package spzx.service.impl;

import com.atguigu.spzx.model.dto.system.AssginRoleDto;
import com.atguigu.spzx.model.dto.system.SysRoleDto;
import com.atguigu.spzx.model.entity.system.SysRole;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import spzx.exception.SpzxException;
import spzx.mapper.SysRoleMapper;
import spzx.service.SysRoleService;

import java.util.List;

@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Override
    public PageInfo findByPage(Integer pageNum, Integer pageSize, SysRoleDto sysRoleDto) {
        //1.设置分页参数
        PageHelper.startPage(pageNum, pageSize);
        //2.查询数据
        List<SysRole> list = sysRoleMapper.selectByCondition(sysRoleDto);
        //3.封装PageInfo对象
        return new PageInfo<>(list);
    }

    @Override
    public void addSysRole(SysRole sysRole) {
        //校验当前角色名称是否已存在
        SysRole sysRoleFromDb = sysRoleMapper.selectByRoleName(sysRole.getRoleName());
        if (sysRoleFromDb!=null){
            throw new SpzxException(501,"该角色名称已存在");
        }
        sysRoleMapper.addSysRole(sysRole);
    }

    @Override
    public void deleteById(Long roleId) {
        sysRoleMapper.deleteById(roleId);
    }

    @Override
    public void deleteByIds(List<Long> roleIds) {
        sysRoleMapper.deleteByIds(roleIds);
    }

    @Override
    public void updateSysRole(SysRole sysRole) {
        //修改时，前端传递的角色名称
        String roleName = sysRole.getRoleName();

        SysRole sysRoleFromDb = sysRoleMapper.selectByRoleName(roleName);

        //sysRole.getId() == sysRoleFromDb.getId()   数据库中的该名称的角色，就是当前要修该的角色
        if (sysRoleFromDb!=null && sysRole.getId() != sysRoleFromDb.getId() ){
            throw new SpzxException(502,"该角色名称已存在");
        }

        sysRoleMapper.updateSysRole(sysRole);
    }

    @Override
    public List<SysRole> findAll() {
        return sysRoleMapper.findAll();
    }

    @Override
    public List<Long> findRoleIdListBySysUserId(Long sysUserId) {
        return sysRoleMapper.findRoleIdListBySysUserId(sysUserId);
    }

    @Transactional
    @Override
    public void doAssignRole(AssginRoleDto assginRoleDto) {
        //1.根据用户id,从user_role表中delete删除关系数据
        sysRoleMapper.deleteUserRole(assginRoleDto.getUserId());
        //2.重新建立关系数据insert到user_role表中
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        Long userId = assginRoleDto.getUserId();
        for (Long roleId : roleIdList) {
            sysRoleMapper.addUserRole(userId, roleId);
        }





    }

}
